package com.boesch.electroOffice.business.businessObjectImpl;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.boesch.electroOffice.business.birt.BerichtResource;
import com.boesch.electroOffice.business.birt.ReportRenderer;
import com.boesch.electroOffice.business.businessObject.ReportBusinessObject;
import com.boesch.electroOffice.business.common.BusinessException;
import com.boesch.electroOffice.model.birt.ReportOptions;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class ReportBusinessObjectImpl implements ReportBusinessObject, Serializable {
	
	private static final long serialVersionUID = -8091010573527412861L;
	private static final Log log = LogFactoryUtil.getLog(BerichtResource.class);
	
	private String birtHome;
	private String pathDBDriver;
	private String pathReports;


	public ReportBusinessObjectImpl(String path_engine_home, String path_reports, String path_DB_driver) {
		birtHome = path_engine_home;
		pathDBDriver = path_DB_driver;
		pathReports = path_reports;
	}
	
	public Map<String, File> getReports() {
		File dir;
		Map<String, File> map = new HashMap<String,File>(32, 0.75f);

		dir = getTemplateDirectory();
		if (null != dir) {
			File[] reportFiles = dir.listFiles();
			for (File reportFile : reportFiles) {
				String name = reportFile.getName();
				String[] nameArray = name.split("\\.");
				if (nameArray.length > 0) {
					map.put(nameArray[0], reportFile);
					log.info("List: " + reportFile);
				}
			}
			return map;
		}
		return null;
	}

	public void doRenderReport(ReportOptions option, String fullPath) throws BusinessException {
		renderReportByName(birtHome, pathReports, pathDBDriver, option, fullPath);
	}

	public String getPathReports() {
		return pathReports;
	}

	public void setPathReports(String pathReports) {
		this.pathReports = pathReports;
	}
	
	private void renderReportByName(String birt_home, String report_path, String odaJDBCDriverClassPath,
			ReportOptions option, String fullPath) throws BusinessException {
		option.setReportName(report_path + '/' + option.getReportName());
		ReportRenderer rr = new ReportRenderer(birt_home, report_path, odaJDBCDriverClassPath);
		rr.render(option, fullPath);
	}

	private File getTemplateDirectory() {
		File dir = new File(getPathReports());
		if (dir.exists()) {
			return dir;
		} else {
			return null;
		}
	}
}
